import os
import time
from typing import List

from PyQt6 import QtWidgets
from PyQt6.QtCore import QThreadPool
from PyQt6.QtWidgets import QScrollArea, QVBoxLayout, QWidget

from scripts.WorkSingle import Worker
from scripts.beans import Storyboard
from ui.adapters.AdapterItem import AdapterItem
from ui.adapters.BoardAdapterItem import BoardAdapterItem


class ScrollviewAdapter:
    def __init__(self, scrollview: QScrollArea, onlysrt=False, callback=None):
        super().__init__()
        self.scrollview = scrollview
        self.onlysrt = onlysrt
        self.callback = callback
        self.storyboards: List[Storyboard]
        self.itemholders: List = []

    def load(self, storyboards: List[Storyboard], scrollindex=0):
        self.storyboards = storyboards

        if scrollindex > 0:
            scroll_offset = self.scrollview.verticalScrollBar().value()

        # 创建一个内容部件,将内容部件和布局关联起来，self.gridLayout在UI文件中已创建
        content_widget = QWidget()
        content_widget.setStyleSheet("background-color: rgba(0, 0, 0, 20)")

        content_layout = QVBoxLayout()
        content_layout.setSpacing(4)
        content_layout.setContentsMargins(12, 12, 12, 12)
        content_widget.setLayout(content_layout)
        # 将内容部件设置为滚动区域的子部件
        self.scrollview.setWidget(content_widget)

        self.itemholders.clear()
        for index, bean in enumerate(self.storyboards):
            itemwidget = QWidget()
            if self.onlysrt:
                itemholder = BoardAdapterItem(itemwidget, index, bean, self.callback)
            else:
                itemholder = AdapterItem(itemwidget, index, bean, self.callback)
            self.itemholders.append(itemholder)
            content_layout.addWidget(itemwidget)
        if scrollindex != 0:
            worker = Worker(inner=lambda: (time.sleep(0.01)), callback=lambda a: (self.scrollToWidget(scroll_offset)))
            thread = QThreadPool.globalInstance()
            thread.start(worker)

    def scrollToWidget(self, scroll_offset):
        scroll_bar = self.scrollview.verticalScrollBar()
        self.scrollview.verticalScrollBar()
        if scroll_bar:
            # 计算要滚动到的位置
            # 注意：这只是一个简化的计算，实际应用中可能需要更复杂的逻辑

            # 设置滚动条的位置
            scroll_bar.setValue(scroll_offset)
